import {
  Form,
  Input,
  Checkbox,
  Radio,
  Select,
  Button,
  message,
  Flex,
  Row,
  Col,
  DatePicker,
  Divider,
} from 'antd'
import dayjs from 'dayjs'
import { useForm } from 'antd/lib/form/Form'
import { useEffect, useState } from 'react'
const { Option } = Select
const { RangePicker } = DatePicker
const { TextArea } = Input

type SizeType = Parameters<typeof Form>[0]['size']

const MyForm = ({
  options,
  onSubmit,
  formLayout = 'vertical',
  hideSubmitButton = false,
  disableSubmitButton = false,
  resetButton = false,
}: any) => {
  const [width, setWidth] = useState<any>(globalThis.innerWidth)

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth)
    }

    window.addEventListener('resize', handleResize)

    // 清理函数，组件卸载时执行
    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, []) // 空依赖数组意味着这个effect只在组件挂载和卸载时运行

  const [form] = useForm()
  // 默认值赋值
  const initialValues = options.reduce((acc: any, option: any) => {
    if (Array.isArray(option)) {
      const rowInitialValues = option.reduce((acc1: any, option1: any) => {
        if (option1.initialValue !== undefined) {
          if (option1.type === 'time') {
            acc1[option1.name] = dayjs(option1.initialValue)
          } else {
            acc1[option1.name] = option1.initialValue
          }
        }
        return acc1
      }, {})
      return { ...rowInitialValues, ...acc }
    } else {
      if (option.initialValue !== undefined) {
        if (option.type === 'time') {
          acc[option.name] = dayjs(option.initialValue)
        } else {
          acc[option.name] = option.initialValue
        }
      }
      return acc
    }
  }, {})
  console.log('初始值：', initialValues)
  form.setFieldsValue(initialValues)
  // 提交
  const handleSubmit = async (values: any) => {
    try {
      await onSubmit(values)
      form.resetFields() // 提交后清除表单中的值
      message.success('提交成功')
    } catch (error) {
      console.error('Error submitting form:', error)
      message.error('提交失败，请检查错误')
    }
  }
  const formItem = options.map((option: any, index: any) => {
    if (Array.isArray(option)) {
      const rowFormItems = option.map((option: any) => {
        if (option.hidden) return null // 控制字段显影
        const labelStyle = option.labelStyle || {}
        switch (option.type) {
          case 'text':
            return (
              <Col key={option.name} span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}
                  tooltip={option.tooltip || null}>
                  <Input
                    placeholder={option.placeholder}
                    disabled={option.disabled}
                  />
                </Form.Item>
              </Col>
            )
          case 'select':
            return (
              <Col key={option.name} span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}
                  tooltip={option.tooltip || null}>
                  <Select
                    placeholder={option.placeholder}
                    disabled={option.disabled}>
                    {option.options &&
                      option.options.map((item: any) => (
                        <Option key={item.value} value={item.value}>
                          {item.label}
                        </Option>
                      ))}
                  </Select>
                </Form.Item>
              </Col>
            )
          case 'password':
            return (
              <Col key={option.name} span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}
                  tooltip={option.tooltip || null}>
                  <Input.Password
                    placeholder={option.placeholder}
                    disabled={option.disabled}
                  />
                </Form.Item>
              </Col>
            )
          case 'time':
            return (
              <Col key={option.name} span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}
                  tooltip={option.tooltip || null}>
                  {option.isRange ? (
                    <RangePicker
                      style={{ width: '100%' }}
                      disabled={option.disabled}
                    />
                  ) : (
                    <DatePicker
                      style={{ width: '100%' }}
                      placeholder={option.placeholder}
                      disabled={option.disabled}
                    />
                  )}
                </Form.Item>
              </Col>
            )
          case 'textarea':
            return (
              <Col key={option.name} span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}
                  tooltip={option.tooltip || null}>
                  <TextArea
                    rows={option.rows || 4}
                    placeholder={option.placeholder}
                    disabled={option.disabled}
                    maxLength={option.maxLength || 100}
                    autoSize={{ minRows: 4, maxRows: 6 }}
                  />
                </Form.Item>
              </Col>
            )
          case 'checkbox':
            return (
              <Col key={option.name} span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}
                  tooltip={option.tooltip || null}>
                  <Checkbox.Group
                    options={option.options}
                    disabled={option.disabled}
                    style={
                      width < 600
                        ? { display: 'flex', flexDirection: 'column' }
                        : {}
                    }
                  />
                </Form.Item>
              </Col>
            )
          case 'radio':
            return (
              <Col key={option.name} span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}
                  tooltip={option.tooltip || null}>
                  <Radio.Group
                    options={option.options}
                    disabled={option.disabled}
                    style={
                      width < 600
                        ? { display: 'flex', flexDirection: 'column' }
                        : {}
                    }></Radio.Group>
                </Form.Item>
              </Col>
            )
          default:
            return null
        }
      })
      return (
        <Row key={index} gutter={16}>
          {rowFormItems}
        </Row>
      )
    } else {
      if (option.hidden) return null // 控制字段显影
      const labelStyle = option.labelStyle || {}
      switch (option.type) {
        case 'text':
          return (
            <Row key={option.name} gutter={16}>
              <Col span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}
                  tooltip={option.tooltip || null}>
                  <Input
                    placeholder={option.placeholder}
                    disabled={option.disabled}
                  />
                </Form.Item>
              </Col>
            </Row>
          )
        case 'select':
          return (
            <Row gutter={16} key={option.name}>
              <Col span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}>
                  <Select
                    placeholder={option.placeholder}
                    disabled={option.disabled}>
                    {option.options &&
                      option.options.map((item: any) => (
                        <Option key={item.value} value={item.value}>
                          {item.label}
                        </Option>
                      ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
          )
        case 'password':
          return (
            <Row gutter={16} key={option.name}>
              <Col span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}>
                  <Input.Password
                    placeholder={option.placeholder}
                    disabled={option.disabled}
                  />
                </Form.Item>
              </Col>
            </Row>
          )
        case 'time':
          return (
            <Row gutter={16} key={option.name}>
              <Col span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}>
                  {option.isRange ? (
                    <RangePicker
                      style={{ width: '100%' }}
                      disabled={option.disabled}
                    />
                  ) : (
                    <DatePicker
                      style={{ width: '100%' }}
                      placeholder={option.placeholder}
                      disabled={option.disabled}
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>
          )
        case 'textarea':
          return (
            <Row key={option.name} gutter={16}>
              <Col span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}
                  tooltip={option.tooltip || null}>
                  <TextArea
                    rows={option.rows || 4}
                    placeholder={option.placeholder}
                    disabled={option.disabled}
                    maxLength={option.maxLength || 100}
                    autoSize={{ minRows: 4, maxRows: 6 }}
                  />
                </Form.Item>
              </Col>
            </Row>
          )
        case 'checkbox':
          return (
            <Row key={option.name} gutter={16}>
              <Col key={option.name} span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}
                  tooltip={option.tooltip || null}>
                  <Checkbox.Group
                    options={option.options}
                    disabled={option.disabled}
                    style={
                      width < 600
                        ? { display: 'flex', flexDirection: 'column' }
                        : {}
                    }
                  />
                </Form.Item>
              </Col>
            </Row>
          )
        case 'radio':
          return (
            <Row key={option.name} gutter={16}>
              <Col key={option.name} span={width < 600 ? 24 : option.width}>
                <Form.Item
                  name={option.name}
                  label={<label style={labelStyle}>{option.label}</label>}
                  rules={option.rules || []}
                  tooltip={option.tooltip || null}>
                  <Radio.Group
                    options={option.options}
                    disabled={option.disabled}
                    style={
                      width < 600
                        ? { display: 'flex', flexDirection: 'column' }
                        : {}
                    }
                  />
                </Form.Item>
              </Col>
            </Row>
          )
        case 'divider':
          return (
            <Divider
              key={option.type}
              style={labelStyle}
              orientation={option.orientation}>
              {option.label}
            </Divider>
          )
        default:
          return null
      }
    }
  })
  return (
    <Form
      form={form}
      size={width < 600 ? ('default' as SizeType) : 'large'}
      layout={formLayout}
      className=""
      // initialValues={initialValues}赋默认值
      onFinish={handleSubmit}>
      {formItem}
      {!hideSubmitButton && (
        <Form.Item>
          <Flex justify={width < 600 ? 'center' : 'flex-start'}>
            <Button
              type="primary"
              htmlType="submit"
              disabled={disableSubmitButton}>
              提交
            </Button>
            {resetButton && (
              <Button danger htmlType="reset" style={{ marginLeft: '15px' }}>
                重置
              </Button>
            )}
          </Flex>
        </Form.Item>
      )}
    </Form>
  )
}
export default MyForm
